package com.zzq.service;

import com.zzq.config.K8sInit;
import com.zzq.square.*;
import io.fabric8.kubernetes.api.model.*;
import io.fabric8.kubernetes.api.model.apps.Deployment;
import io.fabric8.kubernetes.api.model.apps.DeploymentBuilder;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.kubernetes.client.ApiClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/*
导入模型
 */
@Service
@Slf4j
public class ModelSquareService {


    @Autowired
    private KubernetesClient client;

    /**
     * 导入模型操作
     * @return
     */
    public boolean importModelInfo(String clusterId, DeploymentBo deploymentBo){
        String metaDataName = deploymentBo.getName();
        String namespace = deploymentBo.getNamespace();
        //labels
        List<ListMapItemBo> labelsList = deploymentBo.getLabels();
        HashMap<String, String> labels = new HashMap<>();
        for (ListMapItemBo listMapItemBo : labelsList) {
            labels.put(listMapItemBo.getKey(),listMapItemBo.getValue());
        }
        int replicas = deploymentBo.getReplicas();
        List<ContainerBo> containerBos = deploymentBo.getTemplate().getContainers();
        String restartPolicy = deploymentBo.getTemplate().getBase().getRestartPolicy();
        List<String> imagePullSecrets = deploymentBo.getTemplate().getImagePullSecrets();
        //处理volume信息
        List<Volume> volumes = new ArrayList<>();
        List<VolumeBo> volumeBos = deploymentBo.getTemplate().getVolumeBos();
        if(CollectionUtils.isNotEmpty(volumeBos)){
            for (VolumeBo volumeBo : volumeBos) {
                //判断是否是pvc类型
                if("pvc".equals(volumeBo.getType())){
                    Volume volume = new Volume();
                    volume.setName(volumeBo.getName());
                    volume.setPersistentVolumeClaim(new PersistentVolumeClaimVolumeSource(volumeBo.getPvcVolume().getName(),false));
                    volumes.add(volume);
                }
            }
        }
        //pull secret
        List<LocalObjectReference> pullSecretsInfo = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(imagePullSecrets)){
            for (String imagePullSecret : imagePullSecrets) {
                pullSecretsInfo.add(new LocalObjectReference(imagePullSecret));
            }
        }
        //处理container
        List<Container> containers = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(containerBos)){
            for (ContainerBo containerBo : containerBos) {
                String image = containerBo.getImage();
                String name = containerBo.getName();
                String imagePullPolicy = containerBo.getImagePullPolicy();
                List<String> commands = containerBo.getCommands();
                List<String> args = containerBo.getArgs();
                //封装ContainerBo信息
                List<ContainerPortBo> ports = containerBo.getPorts();
                List<ContainerPort> containerPorts = new ArrayList<>();
                if(CollectionUtils.isNotEmpty(ports)){
                    for (ContainerPortBo port : ports) {
                        ContainerPort containerPort = new ContainerPort();
                        containerPort.setContainerPort(port.getContainerPort());
                        containerPort.setProtocol(port.getProtocol());
                        containerPort.setName(port.getName());
                        containerPorts.add(containerPort);
                    }
                }
                //封装env的信息
                List<EnvVarBo> envs = containerBo.getEnvs();
                List<EnvVar> envVars = new ArrayList<>();
                if(CollectionUtils.isNotEmpty(envs)){
                    for (EnvVarBo env : envs) {
                        if("default".equals(env.getType())){
                            EnvVar envVar = new EnvVarBuilder().withName(env.getName()).withValue(env.getValue()).build();
                            envVars.add(envVar);
                        }
                    }
                }
                //封装volumentMounts信息
                List<VolumeMountBo> volumeMountBos = containerBo.getVolumeMountBos();
                List<VolumeMount> volumeMounts = new ArrayList<>();
                if(CollectionUtils.isNotEmpty(volumeMountBos)){
                    for (VolumeMountBo volumeMountBo : volumeMountBos) {
                        VolumeMount volumeMount = new VolumeMountBuilder()
                                .withName(volumeMountBo.getMountName())
                                .withMountPath(volumeMountBo.getMountPath()).build();
                        volumeMounts.add(volumeMount);
                    }
                }
                //处理life style postStart commands
                List<String> postStartCommandList = containerBo.getPostStartCommands();
                Lifecycle lifecycle = new Lifecycle();
                if(CollectionUtils.isNotEmpty(postStartCommandList)){
                    LifecycleHandler lifecycleHandler = new LifecycleHandler();
                    ExecAction execAction = new ExecAction();
                    execAction.setCommand(postStartCommandList);
                    lifecycleHandler.setExec(execAction);
                    lifecycle.setPostStart(lifecycleHandler);
                }
                Container container = new ContainerBuilder()
                        .withImage(image)
                        .withCommand(commands)
                        .withLifecycle(lifecycle)
                        .withArgs(args)
                        .withName(name)
                        .withPorts(containerPorts)
                        .withEnv(envVars)
                        .withVolumeMounts(volumeMounts)
                        .withImagePullPolicy(imagePullPolicy)
                        .build();
                containers.add(container);
            }
        }
        Deployment deployment = new DeploymentBuilder()
                .withNewMetadata()
                .withName(metaDataName)
                .withLabels(labels)
                .endMetadata()
                .withNewSpec()
                .withReplicas(replicas)
                .withNewSelector()
                .withMatchLabels(labels)
                .endSelector()
                .withNewTemplate()
                .withNewMetadata()
                .withLabels(labels)
                .endMetadata()
                .withNewSpec()
                .withImagePullSecrets(pullSecretsInfo)
                .withRestartPolicy(restartPolicy)
                .withContainers(containers)
                .withVolumes(volumes)
                .endSpec()
                .endTemplate()
                .endSpec()
                .build();
        Deployment deploy = client.apps().deployments().inNamespace(namespace).resource(deployment).create();
        log.info("deployment:{}",deploy);
        return true;
    }


    public List<String> getCommands(){
        List<String> commands = new ArrayList<>();
        commands.add("/bin/sh");
        commands.add("-c");
        commands.add("sudo su");
        commands.add("sudo code-server --auth none --bind-addr 0.0.0.0:8080 ${WORKSPACE_DIR}");
        return commands;
    }

    public List<String> getLargeModelArgs(){
        List<String> args = new ArrayList<>();
        args.add("curl https://dl.min.io/client/mc/release/linux-amd64/mc --create-dirs -o $HOME/minio-binaries/mc");
        args.add("chmod +x $HOME/minio-binaries/mc");
        args.add("export PATH=$PATH:$HOME/minio-binaries/");
        //设置桶别名
        args.add("mc alias set nx4oss http://nx4oss.ctyunxs.cn {ak} {sk}");
        //拷贝
        args.add("mc cp nx4oss/large-model/ /work/dmx_home/ --recursive --limit-download 100MiB");
        //昇腾环境
        args.add("mc cp nx4oss/large-model/ascend/model-zd-202405132005-AquilaChat-7B-0707-hugging /work/dmx_home/ --recursive --limit-download 100MiB");
//        mc cp nx4oss/large-model/ascend/model-zd-202405132005-AquilaChat-7B-0707-hugging /work/dmx_home/ --recursive --limit-download 100MiB
//        mc cp nx4oss/large-model/ascend/model-zd-202405132005-Baichuan-13B-Chat /work/dmx_home/ --recursive --limit-download 100MiB
//        mc cp nx4oss/large-model/ascend/model-zd-202405132005-ChatGLM2-6B /work/dmx_home/ --recursive --limit-download 100MiB
//        mc cp nx4oss/large-model/ascend/model-zd-202405132005-Llama2-Chinese-13b-Chat-ms /work/dmx_home/ --recursive --limit-download 100MiB
//        mc cp nx4oss/large-model/ascend/model-zd-202405132005-chinese-alpaca-2-13b /work/dmx_home/ --recursive --limit-download 100MiB
//        mc cp nx4oss/large-model/ascend/model-zd-202405132005-llama-3-70b-hf /work/dmx_home/ --recursive --limit-download 100MiB
//        mc cp nx4oss/large-model/ascend/model-zd-202405132005-llama-7b /work/dmx_home/ --recursive --limit-download 100MiB
//        mc cp nx4oss/large-model/ascend/model-zd-202405132005-llama3_model_from_hf /work/dmx_home/ --recursive --limit-download 100MiB
//        mc cp nx4oss/large-model/ascend/model-zd-202405291115-stable-diffusion-2-1 /work/dmx_home/ --recursive --limit-download 100MiB
//        mc cp nx4oss/large-model/ascend/model-zd-202405150949-Chinese-CLIP /work/dmx_home/ --recursive --limit-download 100MiB
//        mc cp nx4oss/large-model/ascend/model-zd-202405150949-LAVIS /work/dmx_home/ --recursive --limit-download 100MiB
//        mc cp nx4oss/large-model/ascend/model-zd-202405150949-OpenCLIP /work/dmx_home/ --recursive --limit-download 100MiB
//        mc cp nx4oss/large-model/ascend/model-zd-202405150949-visualglm-6B /work/dmx_home/ --recursive --limit-download 100MiB
//        mc cp nx4oss/large-model/ascend/model-zd-202405211507-chatglm2_6b_base /work/dmx_home/ --recursive --limit-download 100MiB
//        mc cp nx4oss/large-model/ascend/model-zd-202405211507-llama2_13b_base /work/dmx_home/ --recursive --limit-download 100MiB
//        mc cp nx4oss/large-model/ascend/model-zd-202405211507-llama2_7b_base /work/dmx_home/ --recursive --limit-download 100MiB
//        mc cp nx4oss/large-model/ascend/model-zd-202406070936-llama2_70b_base /work/dmx_home/ --recursive --limit-download 100MiB
//        mc cp nx4oss/large-model/ascend/model-zd-202405211507-qwen_14b_base /work/dmx_home/ --recursive --limit-download 100MiB
//        mc cp nx4oss/large-model/ascend/model-zd-202405211507-qwen_7b_base /work/dmx_home/ --recursive --limit-download 100MiB
//        mc cp nx4oss/large-model/ascend/model-zd-202405291115-bloom_7b_base /work/dmx_home/ --recursive --limit-download 100MiB
//        mc cp nx4oss/large-model/ascend/model-tyg-202405311040-telechat-12B /work/dmx_home/ --recursive --limit-download 100MiB
//        mc cp nx4oss/large-model/ascend/model-tyg-202405311040-telechat-7B /work/dmx_home/ --recursive --limit-download 100MiB
//        mc cp nx4oss/large-model/ascend/model-zd-202406201433-ms-qwen1.5_72b_base /work/dmx_home/ --recursive --limit-download 100MiB
//        mc cp nx4oss/large-model/ascend/model-zd-202406201429-ms-telechat_12b_base /work/dmx_home/ --recursive --limit-download 100MiB
//        mc cp nx4oss/large-model/ascend/model-zd-202406201432-ms-telechat_7b_base /work/dmx_home/ --recursive --limit-download 100MiB
//        mc cp nx4oss/large-model/ascend/model-zd-202406201433-ms-chatglm3_6b_base /work/dmx_home/ --recursive --limit-download 100MiB

        return args;
    }
}
